<?php
require_once 'defines.php';
require_once 'JedimusicPDO.php';

class User 
{
    public static function login($username, $password) {
        //TODO devolver valores segun que haya pasado

        $clean = array();//array limpio para no utilizar globales GET y POST

        $clean['username'] = strip_tags(substr($username, 0, 100));
        $clean['password'] = strip_tags(substr($password, 0, 255));
        $clean['password'] = crypt(
                            hash("sha512", SALT.$clean['password'].SALT_BACK),
                            md5($clean['username'])
                            );
        $db = JedimusicPDO::getInstance();

        $query = $db->prepare("
            SELECT password
            FROM users
            WHERE username = :username");
        $query->bindParam(':username', $clean['username']);
        if ($query->execute()) {
            $result = $query->fetch(PDO::FETCH_NUM);
            if ($result) {
                if ($result[0] != $clean['password']) {
                    return LOGIN_FAILURE;
                }
                else {//login correcto
                    return LOGIN_SUCCESS;
                }
            }
            else {//usuario no existe
                return LOGIN_FAILURE;
            }
        }
        else {//la consulta ha fallado
            return QUERY_ERROR;
        }
    }
    
    public static function register($username, $password, $email) {
        $clean = array();
        $clean['username'] = $username;//ya se controla luego
        $clean['password'] = strip_tags($password);
        $clean['email'] = strip_tags($email);
        
        $db = JedimusicPDO::getInstance();
        
        $validSymbols = array ('_','-','+','[',']','.',' ');
        if (!ctype_alnum(str_replace($validSymbols, '', $clean['username']))
            || strlen($clean['username']) > 100) {
            //solo se permiten letras, numeros ,espacios, y los simbolos _-+[].
            //y no mas de 100 letras
            return FORMAT_USERNAME_FAILURE;
        }
        if (strlen($clean['password']) > 255) {
            //no mas de 255 simbolos
            //ya se ha avisado de la fuerza del password en el formulario
            return FORMAT_PASSWORD_FAILURE;
        }
        
        $pattern = "/^[^@]+@[a-zA-Z0-9._-]+\.[a-zA-Z]+$/";
        if (!preg_match($pattern, $clean['email'])) {
            //mira si el formato es correcto
            //y no pasar de 255(limite real es 256(64 max nombre + 255 max dom))
            return FORMAT_EMAIL_FAILURE;
        }
        
        $query = $db->prepare("
            SELECT username
            FROM users
            WHERE username = :username");
        $query->bindParam(':username', $clean['username']);
        if ($query->execute()) {
            $result = $query->fetch(PDO::FETCH_NUM);
            if ($result) {//username ya usado
                return USERNAME_USED;
            }
        }
        else {//la consulta ha fallado
            return QUERY_ERROR;
        }
        
        $query = $db->prepare("
            SELECT email
            FROM users
            WHERE email = :email");
        $query->bindParam(':email', $clean['email']);
        if ($query->execute()) {
            $result = $query->fetch(PDO::FETCH_NUM);
            if ($result) {//email ya usado
                return EMAIL_USED;
            }
        }
        else {//la consulta ha fallado
            return QUERY_ERROR;
        }
        
        //datos correctos, pasamos a registrar
        //la clave se guarda encriptada
        $clean['password'] = crypt(
                            hash("sha512", SALT.$clean['password'].SALT_BACK),
                            md5($clean['username'])
                            );
        $query = $db->prepare("
            INSERT INTO users(username, password, email) 
            VALUES (:username, :password, :email)");
        $query->bindParam(':username', $clean['username']);
        $query->bindParam(':password', $clean['password']);
        $query->bindParam(':email', $clean['email']);
        if (!$query->execute()) return QUERY_ERROR;
        
        return REGISTER_SUCCESS;
    }

}
?>
